package com.zhoug.player3.hik;

import android.text.TextUtils;


import com.hikvision.hatomplayer.DefaultHatomPlayer;
import com.hikvision.hatomplayer.HatomPlayer;
import com.hikvision.hatomplayer.PlayCallback;
import com.hikvision.hatomplayer.PlayConfig;
import com.zhoug.common3.Logger;
import com.zhoug.player3.core.OnTalkListener;
import com.zhoug.player3.core.PlayError;
import com.zhoug.player3.core.utils.ThreadUtils;

import java.util.Objects;

import androidx.annotation.NonNull;

/**
 * 对讲封装
 */
public class HikTalkHelper {
    private static final String TAG = ">>>HikTalkHelper";
    private HatomPlayer mPlayer;
    private String mTalkUrl;//对讲url
    private boolean talking = false;//正在对讲
    private OnTalkListener mOnTalkListener;

    public HikTalkHelper(HatomPlayer player) {
        this.mPlayer = player;
    }

    public HikTalkHelper() {
    }

    private void init() {
        if (mPlayer != null) {
            Logger.d(TAG, "initPlayer:无需重复初始化播放器");
            return;
        }
        mPlayer = new DefaultHatomPlayer();
        PlayConfig playConfig = new PlayConfig();
        //使用硬解码
        playConfig.hardDecode = true;
        //开启智能信息
        playConfig.privateData = true;
        //设置播放参数
        mPlayer.setPlayConfig(playConfig);
    }


    public void setPlayer(HatomPlayer player) {
        this.mPlayer = player;
    }

    /**
     * 设置对讲url
     *
     * @param talkUrl
     */
    public void setTalkUrl(String talkUrl) {
        this.mTalkUrl = talkUrl;
    }

    /**
     * 开启对讲
     */
    public void startVoiceTalk() {
        if (talking) {
            Logger.d(TAG, "startVoiceTalk:正在对讲...");
            return;
        }
        if (TextUtils.isEmpty(mTalkUrl)) {
            invokeOnTalkListener(OnTalkListener.FAILED, "对讲url为空");
            return;
        }
        if (mPlayer == null) {
            init();
        }
        //设置对讲回调
        mPlayer.setVoiceStatusCallback(mVoiceTalkCallback);
        //
        mPlayer.setVoiceDataSource(mTalkUrl, null);
        mPlayer.enableAudio(true);
        invokeOnTalkListener(OnTalkListener.LOADING, null);
        _startVoiceTalk();

    }

    /**
     * 关闭对讲
     */
    public void stopVoiceTalk() {
        if (talking && mPlayer != null) {
            invokeOnTalkListener(OnTalkListener.CLOSE, null);
            _stopVoiceTalk();
            talking = false;
        }
    }


    private final PlayCallback.VoiceTalkCallback mVoiceTalkCallback = new PlayCallback.VoiceTalkCallback() {
        @Override
        public void onTalkStatus(@NonNull PlayCallback.Status status, String errorCode) {
            //播放结果回调
            //status 共三种状态：SUCCESS（开启对讲成功）、FAILED（开启对讲失败）、EXCEPTION（取流异常）
            //错误码，只有 FAILED 和 EXCEPTION 才有值
            //注意：回调仍为子线程
            String errorMsg = null;
            int code = 0;
            if (!TextUtils.isEmpty(errorCode)) {
                errorCode = HikErrors.errorCodeToHexString(errorCode);
                errorMsg = HikErrors.getErrorMsg(errorCode);
                if (Objects.equals(HikErrors.URL_EXPIRE, errorCode)) {
                    code = PlayError.URL_EXPIRE;
                }
            }
            switch (status) {
                case SUCCESS:
                    talking = true;
                    invokeOnTalkListener(OnTalkListener.SUCCESS, "正在对讲中");
                    break;
                case FAILED:
                    talking = false;
                    invokeOnTalkListener(OnTalkListener.FAILED, "开启对讲失败:" + errorMsg);
                    break;
                case EXCEPTION:
                    talking = false;
                    invokeOnTalkListener(OnTalkListener.EXCEPTION, "对讲发生异常:" + errorMsg);
                    if (mPlayer != null) {
                        mPlayer.stopVoiceTalk();// 注意:异常时关闭对讲
                    }
                    break;

            }


        }
    };

    public boolean isTalking(){
        return talking;
    }

    public void setOnTalkListener(OnTalkListener onTalkListener) {
        this.mOnTalkListener = onTalkListener;
    }

    /**
     * * 对讲监听
     */
    private void invokeOnTalkListener(int status, String error) {
        if (mOnTalkListener != null) {
            ThreadUtils.runMainThread(() -> mOnTalkListener.onTalkCallback(status, error));
        }
    }

    private void _startVoiceTalk() {
        if (mPlayer != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (this) {
                        if (mPlayer != null) {
                            mPlayer.startVoiceTalk();
                        }
                    }
                }
            }).start();
        }
    }

    private void _stopVoiceTalk() {
        if (mPlayer != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (this) {
                        if (mPlayer != null) {
                            mPlayer.stopVoiceTalk();
                        }
                    }
                }
            }).start();
        }
    }
}
